package com.dorukdestan.p2pshare.storage;

import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import com.dorukdestan.p2pshare.logger.Logger;
import com.dorukdestan.p2pshare.model.DownloadingFile;

public class DownloadQueue {

	private static Logger logger;
	private static HashMap<String, DownloadingFile> downloadQueueUnsynchronized;
	private static Map<String, DownloadingFile> downloadQueue;

	static{
		logger = new Logger(DownloadQueue.class);
		downloadQueueUnsynchronized = new HashMap<String, DownloadingFile>();
		downloadQueue = Collections.synchronizedMap(downloadQueueUnsynchronized);
	}

	public static void handleIncomingFileChunk(String fileHash, String fileIndex, String data){
		addChunkToFile(fileHash, fileIndex, data);
	}
	
	public static DownloadingFile createNewDownload(String fileHash, long fileLength, String fileName, ArrayList<InetAddress> peers){
		DownloadingFile downloadingFile = new DownloadingFile(fileHash, fileLength, fileName, peers);
		downloadQueue.put(fileHash, downloadingFile);
		
		logger.debug("New DownloadingFile is created. Length " + fileLength);
		
		return downloadingFile;
	}
	
	private static void addChunkToFile(String fileHash, String index, String data){
		logger.debug("Adding chunk");
		//find download process
		DownloadingFile downloadingFile = downloadQueue.get(fileHash);
		
		//add chunk to downloading file
		downloadingFile.addChunk(Integer.parseInt(index), data);
	}
	
	public static Map<String, DownloadingFile> getDownloadQueue() {
		return downloadQueue;
	}
}
